package Demo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Compute extends JFrame implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField tf;
	private JButton clear;
	private boolean isNew=true;
	private double result=0;
	private String preOperator="+";
	public Compute() {
		setSize(300, 300);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		JPanel top = new JPanel();
		top.setLayout(new BorderLayout());
		Font font = new Font("微软雅黑", Font.TRUETYPE_FONT, 24);
		tf = new JTextField("0");
		tf.setHorizontalAlignment(JTextField.RIGHT);
		tf.setEnabled(false);
		tf.setDisabledTextColor(Color.black);
		clear = new JButton("清除");
		clear.addActionListener(this);
		tf.setFont(font);
		clear.setFont(font);
		top.add(tf);
		top.add(clear, BorderLayout.EAST);
		add(top, BorderLayout.NORTH);
		String[] str = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", ".", "=", "/" };
		JPanel center = new JPanel();
		center.setLayout(new GridLayout(4, 4));
		for (String s : str) {
			JButton bt = new JButton(s);
			bt.setFont(font);
			bt.setBackground(new Color(0xABACFA));
			bt.setForeground(new Color(0xFFFFFF));
			bt.addActionListener(this);
			center.add(bt);
		}
		add(center);
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				new Compute();
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String acmd = e.getActionCommand();
		if ("0.123456789".indexOf(acmd) >= 0)
			numInput(acmd);
		else if (acmd.equals("清除")) {
			tf.setText("0");
		}
		else{
			caculator(acmd);
		}
	}

	private void caculator(String op) {
		isNew=true;
		double num=Double.valueOf(tf.getText());
		switch(preOperator){
		case "+":result+=num;break;
		case "-":result-=num;break;
		case "*":result*=num;break;
		case "/":result/=num;break;
		}
		String rst=String.valueOf(result);
		if(rst.endsWith(".0")){
			rst=rst.substring(0, rst.length()-2);
		}
		tf.setText(rst);
		preOperator=op;
	}

	private void numInput(String num) {
		String yuan = tf.getText();
		if(isNew) yuan="0";
		if (yuan.equals("0")) {
			isNew=false;
			if (!num.equals("0")) {
				if(num.equals(".")) tf.setText("0.");
				else tf.setText(num);
				return;
			}			
		}
		else {
			if(yuan.indexOf(".")>=0&&num.equals("."))return;
			tf.setText(yuan + num);
		}
	}

}
